#include "treeapp.h"
#include "ui_treeapp.h"
#include <QString>
#include <QFileDialog>
#include <QMessageBox>
#include <QTextStream>
#include <QStringList>

#include <QFile>
#include <QByteArray>

#include <QDebug>
#include <fstream>
#include "node.h"
#include "treemodel.h"

#include <QRegExp>
#include <memory>
#include <QColor>


TreeApp::TreeApp(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::TreeApp)
{
    ui->setupUi(this);
    model = new TreeModel(this);

    QStringList cols;
    cols<<"objectName"<<"id";
    model->setColumns(cols);

    ui->treeView->setModel(model);
    //ui->treeView->hideColumn(1);
}

TreeApp::~TreeApp()
{
    delete ui;
}


void TreeApp::on_actionSelect_a_file_triggered()
{
    QString filter = "*.txt";
    QString filename = QFileDialog::getOpenFileName(0, "OpenDialog",QDir::homePath(),filter);
    QStringList strs;//for strings from a file

    if(!filename.isNull())
    {
        QFile file(filename);

        if(!file.open(QFile::ReadOnly | QFile::Text))
        {
            QMessageBox::warning(this,"Error","File not open");
            return;
        }

        QTextStream in(&file);

        while(!in.atEnd ())
        {
            QString str = in.readLine();
            if(!str.isEmpty())
                strs.push_back(str);
        }
        file.close();

    }

    for (QString& data : strs) //обработка каждой строки считанной из файла
        //(TODO - реализовать проверку на соответствие критериям и действия при несоответствии)
    {
        QRegExp space(":");
        QStringList forNode = data.split(space);

        QObject * newItem = new Node();
        Node* node = static_cast<Node*>(newItem);

        //id
        unsigned int id = forNode.at(0).toInt();//промежуточная переменная нужна?
        newItem->setProperty("id",id);//убрать
        node->setId(id);

        //pld
        QString pldStr = forNode.at(1);//убрать?
        node->setPld(pldStr.toInt());

        //caption
        newItem->setObjectName(forNode.at(2));

        //status
        bool status = forNode.at(3).toInt();
        node->setStatus(status);

        //message
        node->setMessage(forNode.at(4));

        if(node->pld() < 0)
        {
            model->AddItem(newItem, QModelIndex());
            newItem->setParent(model->rootItem());
        }
        else
        {

            //QModelIndex ind = model->match(model->index(0,1),Qt::DisplayRole,QVariant(pldStr), -1).first();//переделать
            QModelIndex ind = model->IndexById(pldStr);


            if(model->objByIndex(ind)->parent() == model->rootItem())
            {
                 model->AddItem(newItem,ind);
            }
            else
            {
                //TODO
                QString mess = "You tried to make more than 2 levels of nesting. This feature is under development. You can still see the first 2 levels";
                QMessageBox::information(this,"Info",mess);

            }
        }
    }
}


void TreeApp::doubleClicked(QModelIndex ind)
{
    Node* Nnode = static_cast<Node*>(model->objByIndex(ind));
    if(Nnode->status())
        QMessageBox::information(this,"Info",Nnode->message());
}
